<script setup>
import { getList, createApi, updateApi, updateStatusApi, deleteApi, deletAllApi } from '@/api/skus'
import { ref, onMounted } from 'vue'
import FromDrawer from '@/components/from-drawer.vue'
import { toast } from '@/utils/elnotification'
import ListHeader from '@/components/list-header.vue'
import TagInput from '@/components/tag-input.vue'

//绑定表格数据
const tableData = ref([])
//总页数
const total = ref(0)
//当前页
const currentPage = ref(1)
//加载动画
const loading = ref(false)
//公告标题
const title1 = ref('')

//获取表格数据
const getData = async (p = null) => {
  if (typeof p === 'number') {
    currentPage.value = p
  }
  loading.value = true
  try {
    const res = await getList(currentPage.value)
    tableData.value = res.list
    total.value = res.totalCount
  } catch (error) {
  } finally {
    loading.value = false
  }
}

//删除公告
const onDelete = async (row) => {
  fromDrawerRef.value.showLoading()
  try {
    await deleteApi(row.id)
    toast('删除成功')
    getData(1)
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    fromDrawerRef.value.hideLoading()
  }
  console.log(row)
}

//新增公告
const fromDrawerRef = ref(null)
const onAdd = () => {
  title1.value = '新增规格'
  changId.value = 0
  fromDrawerRef.value.open()
  form.value = {
    name: '',
    status: 1,
    default: '',
    order: 50
  }
}

//表单部分
const formRef = ref(null)
const form = ref({
  name: '',
  status: 1,
  default: '',
  order: 50
})

//表单校验规则
const rules = {
  name: [{ required: true, message: '规格昵称不能为空', trigger: 'blur' }],
  default: [{ required: true, message: '规格值不能为空', trigger: 'blur' }]
}

//确认提交
const onSubmit = async () => {
  const val = await formRef.value.validate((val) => val)
  if (!val) return
  fromDrawerRef.value.showLoading()
  if (changId.value !== 0) {
    try {
      await updateApi(changId.value, { ...form.value })
      toast('编辑成功')
      getData(1)
    } catch (error) {
      toast('编辑失败', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  } else {
    try {
      await createApi({ ...form.value })
      toast('新增成功')
      getData(1)
    } catch (error) {
      toast('新增失败', 'error')
    } finally {
      fromDrawerRef.value.hideLoading()
    }
  }
}

//修改公告
const changId = ref(0)
const onChange = (row) => {
  title1.value = '修改规格'
  const { order, name, status, id } = row
  form.value = {
    name,
    status,
    order,
    default: row.default
  }
  changId.value = id
  fromDrawerRef.value.open()
}

//修改状态
const onChangeStatus = async (status, row) => {
  row.statusLoading = true
  try {
    await updateStatusApi(row.id, status)
    toast('修改状态成功')
    row.status = status
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    row.statusLoading = false
  }
}

//多选
const ids = ref([])
const handleSelectionChange = (item) => {
  ids.value = item.map((i) => i.id)
  // console.log(item.map((i) => i.id))
}

//删除多选
const onDeleteAll = async () => {
  if (ids.value.length === 0) return toast('请选择所需要删除的数据', 'error')
  try {
    await deletAllApi(ids.value)
    toast('批量删除成功')
    getData(1)
  } catch (error) {
    toast('仅供演示，来到此步表示操作成功', 'error')
  } finally {
    ids.value = []
  }
}

onMounted(() => {
  getData()
})
</script>

<template>
  <el-card shadow="never" class="border-0" v-loading="loading">
    <ListHeader @create="onAdd" @refresh="getData" delete @deleteAll="onDeleteAll"></ListHeader>
  </el-card>
  <el-table @selection-change="handleSelectionChange" :data="tableData" stripe style="width: 100%">
    <el-table-column type="selection" width="55" fixed />
    <el-table-column prop="name" label="规格名称" />
    <el-table-column prop="default" label="规格值" />
    <el-table-column prop="order" label="排序" />
    <el-table-column label="状态" width="120">
      <template #default="{ row }">
        <el-switch v-model="row.status" :active-value="1" :inactive-value="0" @change="onChangeStatus($event, row)"
          :loading="row.statusLoading">
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="250" align="center">
      <template #default="scoped">
        <el-button type="primary" size="small" text @click="onChange(scoped.row)">修改</el-button>
        <el-popconfirm title="是否要删除该规格？" confirm-button-text="确认" cancel-button-text="取消" @confirm="onDelete(scoped.row)">
          <template #reference>
            <el-button type="primary" size="small" text>删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <div class="flex justify-center justify-center mt-5">
    <el-pagination @current-change="getData" :current-page="currentPage" background layout="prev,pager,next"
      :total="total" />
  </div>
  <FromDrawer destroy-on-close ref="fromDrawerRef" :title="title1" @submit="onSubmit">
    <el-form :model="form" ref="formRef" :rules="rules" label-width="80px" :inline="false">
      <el-form-item label="规格名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入规格名称"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="order">
        <el-input-number v-model="form.order" :min="1" :max="100" />
      </el-form-item>
      <el-form-item label="状态">
        <el-switch v-model="form.status" :active-value="1" :inactive-value="0"> </el-switch>
      </el-form-item>
      <el-form-item label="规格值" prop="default">
        <TagInput v-model="form.default"></TagInput>
      </el-form-item>
    </el-form>
  </FromDrawer>
</template>

<style scoped></style>
